package protoc

import (
	"bufio"
	"bytes"
	"encoding/binary"
)

const (
	PACKET_MIN_LEN      int = 6
	PACKET_DATA_MAX_LEN int = 4096
)

type Packet struct {
	//命令
	Cmd uint8
	//协议版本
	ProtocolVer uint8
	//待命时间
	OnCallTime uint8
	//消息长度
	MsgLen uint8
	//消息体
	Data []byte
}

func (p *Packet) NewPacket(cmd, protocolVer, onCallTime, msgLen uint8, data []byte) *Packet {
	return &Packet{
		Cmd:         cmd,
		ProtocolVer: protocolVer,
		OnCallTime:  onCallTime,
		MsgLen:      msgLen,
		Data:        data,
	}
}

// Decode 解码消息
func (p *Packet) decodePacket(reader *bufio.Reader) (string, error) {

	// 读取消息的长度
	lengthByte, _ := reader.Peek(6) // 读取前6个字节的数据

	lengthBuff := bytes.NewBuffer(lengthByte)

	var length int32
	err := binary.Read(lengthBuff, binary.LittleEndian, &length)
	if err != nil {
		return "", err
	}
	// Buffered返回缓冲中现有的可读取的字节数。
	if int32(reader.Buffered()) < length+6 {
		return "", err
	}

	// 读取真正的消息数据
	pack := make([]byte, int(6+length))
	_, err = reader.Read(pack)
	if err != nil {
		return "", err
	}
	return string(pack[4:]), nil
}
